// pages/indexSearchShop/indexSearchShop.js
let url_js = require("../../utils/url.js");
let common_js = require("../../utils/common.js");
let user_js = require("../../utils/user.js");
let ubt_js = require("../../utils/ubt.js");
let name_js = require("../../utils/ubtButtonName.js");
let api = require("../../utils/apiRequest.js");
let const_js = require("../../utils/const.js");
let sys_js = require("../../utils/system.js");
let util_js = require("../../utils/util.js");
let page_js = require("../../utils/pageOptions.js");
let wxp = require("../../utils/wxp.js");
let notificationCenter = require('../../thridLib/WxNotificationCenter.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,
    loactionCityInfo: null,
    contentStatus: -1, //1有数据
    isSearching: false,
    keyWord: '',
    noShopUrl: url_js.imgUrl + "no_shop.png",
    searchingStatus: -1, //0:搜索没有内容 1有内容
    unSearchStatus: -1, //0:无数据，1有数据
    myZtdInfo: null,
    noLocationUrl: url_js.imgUrl + "no_location.png",
    shopNearbyList: [],
    nearbyPageInfo: {
      curPage: 1,
      pageSize: 10,
      noMore: false
    },
    searchPageInfo: {
      curPage: 1,
      pageSize: 10,
      noMore: false
    },
    searchResultList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //业务埋点
    ubt_js.myPageView(common_js.currentPageName(), options);
    //1.禁止转发
    wx.hideShareMenu();
    //2.注册通知----首次进入，等code获取完成
    this.registNotification();
    // 3.初始化数据
    this.initData(options);
  },

  onShow: function () {
    //获取用户定位
    if (user_js.getCode()) {
      this.getUserLocation();
    }
  },

  //注册通知，当自提点切换的时候，更新数据
  registNotification: function () {
    let that = this;
    notificationCenter.addNotification(const_js.getCodeSucessNoti, that.getCodeSuccess, that);
  },

  //微信获取code成功
  getCodeSuccess: function () {
    //3.初始化数据
    this.initData();
    this.getUserLocation();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //移除通知
    let that = this;
    notificationCenter.removeNotification(const_js.getCodeSucessNoti, that);
    // 业务埋点
    ubt_js.myPageViewOut(common_js.currentPageName());
  },

  //初始化数据
  initData: function (options) {
    //1.请求code
    if (!user_js.getCode()) {
      api.getAccessToken();
    } else {
      let tempUserInfo = user_js.userInfo();
      this.setData({
        userInfo: tempUserInfo,
      });
    }
  },

  //点击省市信息
  onCityName: function () {
    this.getUserLocation(true);
  },

  //获取用户定位
  getUserLocation: function (openInlineMap) {
    // 获取设置
    wxp.getSetting().then(res => {
      // 位置设置
      if (!res.authSetting['scope.userLocation']) {
        // 提前授权用户位置信息
        this.authorizeUserLocation(openInlineMap);
      } else {
        this.getWxLocation(openInlineMap);
      }
    }).catch(err => {
      common_js.showToast("获取当前设置失败，请重试!");
    })
  },

  // 提前授权用户位置信息
  authorizeUserLocation(openInlineMap) {
    wxp.authorize({
      scope: 'scope.userLocation'
    }).then(res => {
      this.getWxLocation(openInlineMap);
    }).catch(err => {
      //授权拒绝 
      let firstAuthDeny = err.errMsg.indexOf("fail auth deny") != -1;
      this.checkHasRole(firstAuthDeny);
    });
  },

  // 打开wx位置
  getWxLocation(openInlineMap) {
    wxp.getLocation().then(res => {
      if (openInlineMap) {
        this.openWechatLocation(res, openInlineMap);
      } else {
        this.requestToGetLocationSaveUrl(res);
      }
    }).catch(err => {
      common_js.showToast("获取当前位置失败，请重试!")
    });
  },

  //打开微信内置地图
  openWechatLocation: function (res, openInlineMap) {
    const latitude = res.latitude;
    const longitude = res.longitude;
    //2.打开地图选择位置
    wx.chooseLocation({
      latitude: latitude,
      longitude: longitude,
      success: res => {
        //1.设置参数
        this.requestToGetLocationSaveUrl(res);
      },
      fail: res => {
        let canceled = res.errMsg.indexOf("cancel") != -1;
        if (canceled) {
          common_js.showModal("亲，我们未获得您的位置，请重新选择", null, true, null, null, () => {
            this.getUserLocation(openInlineMap);
          });
        }
      }
    });
  },

  //处理拒绝地图授权
  handleMapFailAuthDeny: function (res) {
    //授权拒绝
    let firstAuthDeny = res.errMsg.indexOf("fail auth deny") != -1;
    if (firstAuthDeny) return;
    //提示打开设置
    common_js.showModal("亲，我们未获得您的位置授权，即将打开设置", null, true, null, null, () => {
      wx.openSetting({
        success: res => {
          let isOpenUserLocation = res.authSetting['scope.userLocation'];
          // 选择自提点
          if (isOpenUserLocation) {
            this.getUserLocation();
          }
        }
      })
    })
  },

  // 检查时候授权位置
  checkHasRole(firstAuthDeny) {
    if (firstAuthDeny) {
      this.goSelectZtPositionWithNoauther();
      return;
    }

    wxp.showModal({
      showCancel: false,
      content: '亲，我们未获得您的位置授权，即将打开设置'
    }).then(res => {
      this.goSelectZtPositionWithNoauther();
    }).catch(err => {
      common_js.log(err);
    });
  },

  // 打开设定定位权限页面
  goSelectZtPositionWithNoauther() {
    // 打开设置页面
    let ztdObj = {};
    ztdObj.autherStatus = 0;
    wx.navigateTo({
      url: '/pages/selectZtPosition/selectZtPosition?ztdOjb=' + common_js.jsonStringify(ztdObj)
    });
  },

  //根据当前的经纬度获取locationSaveUrl
  requestToGetLocationSaveUrl: function (location) {
    //1.我的自提点
    let data = {
      code: user_js.getCode(),
      lat: location.latitude,
      lon: location.longitude
    }
    api.wxRequest(url_js.locationSaveUrl, data).then(res => {
      this.handleLocationSaveData(res);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理返回的经纬度数据
  handleLocationSaveData: function (res) {
    if (!res.result) {
      common_js.showToast("经纬度获取失败");
      return;
    }
    this.setData({
      contentStatus: 1,
      loactionCityInfo: res.result
    });
    //根据当前经纬度去请求数据
    this.getRemoteDatas(res.result);
  },

  //网络请求获取数据
  getRemoteDatas: function () {
    //1.获取当前用的是否有自提点
    this.getUserCurrentShop();
    //2.查询附近店铺信息
    this.requestToGetShopList(this.data.nearbyPageInfo.curPage, this.data.nearbyPageInfo.pageSize, this.data.loactionCityInfo.lat, this.data.loactionCityInfo.lon, '', true);
  },

  //跟新我的自提点信息,用于选择完回来更新
  updateMyZtdInfo: function (res) {
    this.setData({
      myZtdInfo: res
    });
  },

  // 获取当前用的的自提点
  getUserCurrentShop() {
    let data = {}
    api.wxRequest(url_js.shopDefaultShopUrl, data).then(res => {
      //自提点存在
      // 1.update info
      this.setData({
        myZtdInfo: res.result
      });
      // 2.返回首页
      this.handleSelectShopData(res.result);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //请求获取附近的自提点
  requestToGetShopList: function (currPage, pageSize, lat, lon, shopName, pullDownRefresh) {
    let data = {
      currPage: currPage,
      lat: lat,
      lon: lon,
      pageSize: pageSize,
      shopName: shopName
    };
    api.wxRequest(url_js.shopListUrl, data).then(res => {
      this.hanldeNearbyShopsData(res, currPage, pullDownRefresh);
      common_js.hidePageLoading(pullDownRefresh);
    }).catch(err => {
      common_js.hidePageLoading(pullDownRefresh);
      common_js.log(err);
    });
  },

  //处理返回的附近的自提点列表
  hanldeNearbyShopsData: function (res, currPage, pullDownRefresh) {
    if (this.data.isSearching) {
      //设置数据
      let tmpShopList = this.data.searchResultList;
      if (pullDownRefresh) {
        tmpShopList = [];
      }
      //pageInfo
      let tmpPageInfo = this.data.searchPageInfo;
      if (res.page.pages <= currPage) {
        tmpPageInfo.noMore = true;
      } else {
        tmpPageInfo.curPage++;
      }
      //list
      if (res.result.length > 0) {
        tmpShopList = tmpShopList.concat(res.result);
        this.setData({
          searchingStatus: 1,
          searchPageInfo: tmpPageInfo,
          searchResultList: tmpShopList
        });
      } else {
        this.setData({
          searchingStatus: 0,
          searchPageInfo: tmpPageInfo
        });
      }
    } else {
      //设置数据
      let tmpShopList = this.data.shopNearbyList;
      if (pullDownRefresh) {
        tmpShopList = [];
      }
      //pageInfo
      let tmpPageInfo = this.data.nearbyPageInfo;
      if (res.page.pages <= currPage) {
        tmpPageInfo.noMore = true;
      } else {
        tmpPageInfo.curPage++;
      }
      //list
      if (res.result.length > 0) {
        tmpShopList = tmpShopList.concat(res.result);
        this.setData({
          nearbyPageInfo: tmpPageInfo,
          shopNearbyList: tmpShopList,
          unSearchStatus: 1
        });
      }
    }
  },

  //选中自提点--type:1附近  2.搜索结果 index为type对应的数组的index
  requestToAddShop: function (cityId, shopId, type, index) {
    let item = null;
    if (type == 1) {
      item = this.data.shopNearbyList[index];
    } else if (type == 2) {
      item = this.data.searchResultList[index];
    }
    if (!item.location.lat || !item.location.lon) {
      wxp.showToast({
        title: "经度或者纬度为空！"
      });
      return;
    }
    let data = {
      cityId: cityId,
      code: user_js.getCode(),
      geoLat: item.location.lat,
      geoLon: item.location.lon,
      shopId: shopId,
    }
    api.wxRequest(url_js.shopSelectShopUrl, data).then(res => {
      this.handleAddShopData(res, type, index);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理添加自提点返回的自提点数据
  handleAddShopData: function (res, type, index) {
    let selectedItem = {};

    if (type == 1) {
      let item = this.data.shopNearbyList[index];
      item.hasJoin = true;
      this.setData({
        shopNearbyList: this.data.shopNearbyList
      });
      selectedItem = item;
    } else {
      let item = this.data.searchResultList[index];
      item.hasJoin = true;
      this.setData({
        searchResultList: this.data.searchResultList
      });
      selectedItem = item;
    }
    //处理选中自提点返回的数据
    this.handleSelectShopData(selectedItem);
    //saveZtd
    this.saveZtd(selectedItem);
    // 重置index,刷新数据
    //2.查询附近店铺信息
    if (this.data.isSearching) {
      this.setData({
        searchPageInfo: {
          curPage: 1,
          pageSize: 10,
          noMore: false
        }
      });
      this.requestToGetShopList(this.data.searchPageInfo.curPage, this.data.searchPageInfo.pageSize, this.data.loactionCityInfo.lat, this.data.loactionCityInfo.lon, this.data.keyWord, true);
    } else {
      this.setData({
        nearbyPageInfo: {
          curPage: 1,
          pageSize: 10,
          noMore: false
        }
      });
      this.requestToGetShopList(this.data.nearbyPageInfo.curPage, this.data.nearbyPageInfo.pageSize, this.data.loactionCityInfo.lat, this.data.loactionCityInfo.lon, '', true);
    }
  },

  // 保存自提点
  saveZtd(selectedItem) {
    //1.存储新的自提点
    let tmpUserInfo = this.data.userInfo;
    tmpUserInfo.ztd = selectedItem;
    user_js.saveUserInfo(tmpUserInfo);

    //1.. post notification
    notificationCenter.postNotificationName(const_js.changeShopSucessNoti);
    this.updateMyZtdInfo(selectedItem);
  },

  //处理选中自提点返回的数据
  handleSelectShopData: function (selectedItem) {
    if (user_js.hasRole()) return;
    if (!selectedItem) return;

    //2.保存当前用户自提点
    let tempUserInfo = user_js.userInfo();
    //0 购物
    tempUserInfo.role = 1;
    tempUserInfo.ztd = selectedItem;
    user_js.saveUserInfo(tempUserInfo);

    //3.根据shareType不同，跳转到不同的页面
    let tmpPageOptions = page_js.pageOptionsInfo();
    if (!tmpPageOptions) {
      wx.reLaunch({
        url: '/pages/index/index',
      })
    } else {
      wx.reLaunch({
        url: tmpPageOptions.url + tmpPageOptions.param
      });
    }
    if (tmpPageOptions) {
      page_js.clearPageOptionsInfo();
    }
  },

  //搜索附近的门店
  bindSearchInput: function (e) {
    let tmpKeyWord = e.detail.value;
    if (tmpKeyWord.length > 0) {
      this.setData({
        isSearching: true,
        searchingStatus: -1,
        keyWord: tmpKeyWord,
      });
    } else {
      this.setData({
        isSearching: false
      })
    }
  },

  //搜索结束
  onSearchDone: function (res) {
    // set data
    if (!this.data.keyWord) return;
    // reset page 
    let tmpPageInfo = this.data.searchPageInfo;
    tmpPageInfo.curPage = 1;
    tmpPageInfo.noMore = false;
    this.setData({
      searchPageInfo: tmpPageInfo
    });

    //根据关键词去搜索
    this.requestToGetShopList(this.data.searchPageInfo.curPage, this.data.searchPageInfo.pageSize, this.data.loactionCityInfo.lat, this.data.loactionCityInfo.lon, this.data.keyWord, true);
  },

  //重新定位
  onRelocation: function () {
    this.getUserLocation();
  },

  //我的自提点
  onMyZtd: function () {
    let item = common_js.jsonStringify(this.data.loactionCityInfo);
    wx.navigateTo({
      url: '../indexMyZtPosition/indexMyZtPosition?locationInfo=' + item
    })
  },

  // 获取用户信息
  onGetUserInfo(e) {
    let userInfo = e.detail.userInfo;
    //2.保存当前用户自提点
    let tempUserInfo = user_js.userInfo();
    tempUserInfo.wxUserInfo = userInfo
    user_js.saveUserInfo(tempUserInfo);

    //更新userInfo
    this.setData({
      userInfo: tempUserInfo
    });

    // 添加自提点
    let params = {
      currentTarget: {
        dataset: {
          index: e.detail.index
        }
      }
    };
    this.onAddNearbyZtd(params);
  },

  //添加自提点
  onAddNearbyZtd: function (e) {
    let index = e.currentTarget.dataset.index;
    let item = this.data.shopNearbyList[index];
    // 提示是否切换自提点
    wxp.showModal({
      title: '确认更换自提点吗？',
      content: '您确定将' + item.address + '设为新的自提点吗？',
      cancelText: '我在想想',
      confirmText: '确认更换',
      confirmColor: '#C7000B'
    }).then(res => {
      //埋点
      ubt_js.myClickButton(common_js.currentPageName(), name_js.indexSearchShopAdd);
      //选择自提点
      this.requestToAddShop(this.data.loactionCityInfo.cityId, item.id, 1, index);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //搜索中添加自提点
  onSearchAddNearbyZtd: function (e) {
    let index = e.currentTarget.dataset.index;
    let item = this.data.searchResultList[index];
    // 提示是否切换自提点
    wxp.showModal({
      title: '确认更换自提点吗？',
      content: '您确定将' + item.address + '设为新的自提点吗？',
      cancelText: '我在想想',
      confirmText: '确认更换',
      confirmColor: '#C7000B'
    }).then(res => {
      //埋点
      ubt_js.myClickButton(common_js.currentPageName(), name_js.indexSearchShopAdd);
      //添加自提点
      this.requestToAddShop(this.data.loactionCityInfo.cityId, item.id, 2, index);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //切换自提点
  onToggleZtd: function (e) {
    //跳转我的自提点列表
    let item = common_js.jsonStringify(this.data.loactionCityInfo);
    wx.navigateTo({
      url: '../indexMyZtPosition/indexMyZtPosition?locationInfo=' + item
    })
  },

  //联系团长
  contactDz: function () {
    if (!this.data.myZtdInfo.mobile) {
      common_js.showToast("电话不存在！");
      return
    }
    //打电话
    wx.makePhoneCall({
      phoneNumber: this.data.myZtdInfo.mobile
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (!this.data.isSearching) {
      if (this.data.unSearchStatus == 1) {
        if (this.data.nearbyPageInfo.noMore) return;
        //请求数据
        this.requestToGetShopList(this.data.nearbyPageInfo.curPage, this.data.nearbyPageInfo.pageSize, this.data.loactionCityInfo.lat, this.data.loactionCityInfo.lon, '');
      }
    } else {
      //搜索中的状态
      if (this.data.searchingStatus == 1) {
        if (this.data.searchPageInfo.noMore) return;
        //请求数据
        this.requestToGetShopList(this.data.searchPageInfo.curPage, this.data.searchPageInfo.pageSize, this.data.loactionCityInfo.lat, this.data.loactionCityInfo.lon, this.data.keyWord);
      }
    }
  }
})